import sys
from tkinter import messagebox

from app.init_var import InitVar


class AppController:
    def __init__(self, view):
        self.image_server_var = None
        self.view = view
        self.is_btn = False # 是否按下按钮, 防止重复点击
        self.image_server()

    def exit_program(self, event=None):
        """
        退出程序
        """
        print('ESC退出程序')
        # 获取图片服务器对象
        if hasattr(self, 'image_server_var') and self.image_server_var:
            self.image_server_var.stop()
            print('图片服务器已停止')
        sys.exit(0)

    def image_server(self):
        """
        启动图片服务器
        """
        try:
            if InitVar.image_switch:
                # 启动图片服务器
                from app.image_server import ImageServer
                self.image_server_var = ImageServer(port=InitVar.image_server_port, url=InitVar.image_server_url)
                self.image_server_var.start()
        except Exception as e:
            messagebox.showerror("错误", f"无法启动图片服务器: {e}")
            print(f"无法启动图片服务器: {e}")
            self.image_server_var = None

    def on_button_press(self, event):
        # 执行当前视图按钮按下
        if self.is_btn:
            return
        self.is_btn = True
        self.view.now_view.on_button_press(event=event)
    def on_button_release(self,event):
        # 执行当前视图按钮释放
        self.is_btn = False
        self.view.now_view.on_button_release(event=event)
